package com.wn.controller;

import com.wn.bean.Result;
import com.wn.utils.QiNiuUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Api(tags = "文件上传")
public class UploadController{

    // @RequestPart 接受 前端 传递过来的图片

    /**
     * @RequestPart MultipartFile file  接受图片文件
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestPart MultipartFile file) throws IOException {
        // 1. 获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 2. 重新设置文件的名称
        String uuid = UUID.randomUUID().toString();
        // 文件的名称 = uuid + 源文件的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = uuid + substring;
        fileName.replaceAll("-", "");

        // 3. 调用图片上传的工具类
        String url = QiNiuUploadUtils.uploadFile(file.getBytes(), fileName);

        // 4. 响应数据
        return Result.ok(url);
    }

    @ApiOperation("删除图片")
    @GetMapping("/delete")
    public Result delete(String fileName){
        QiNiuUploadUtils.deleteFile(fileName);
        return Result.ok();
    }
}